package com.bite.common.utils;

import com.bite.common.exception.BlogException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.concurrent.TimeUnit;

@Slf4j
public class RedisUtils {
    private final StringRedisTemplate template;

    private static final String DELIMITER = ":";

    public RedisUtils(StringRedisTemplate template){
        this.template = template;
    }

    public void set(String key, String val){
        try {
            if (checkParam(key, val)){
                throw new BlogException("参数异常！");
            }
            template.opsForValue().set(key,val);
        }catch (Exception e){
            log.error("RedisUtils.set: key:{}, value:{}", key,val,e);
        }
    }

    public void set(String key,String val,long timeout){
        try {
            if (checkParam(key, val) && timeout > 0){
                throw new BlogException("参数异常！");
            }
            template.opsForValue().set(key,val,timeout, TimeUnit.SECONDS);
        }catch (Exception e){
            log.error("RedisUtils.set: key:{}, value:{}, timeout:{}", key,val,timeout,e);
        }
    }

    public Boolean contains(String key){
        try {
            if (checkParam(key)){
                throw new BlogException("参数异常！");
            }
            return template.hasKey(key);
        }catch (Exception e){
            log.error("RedisUtils.contains: key:{}", key,e);
            return false;
        }
    }

    private boolean checkParam(String... s){
        for (String str : s){
            if (str == null){
                return true;
            }
        }
        return false;
    }

    public String get(String key){
        try {
            if (key == null){
                throw new BlogException("参数异常！");
            }
            return template.opsForValue().get(key);
        }catch (Exception e) {
            log.error("RedisUtils.get: key:{}", key, e);
            return null;
        }
    }

    public String keyBuilder(String prefix, String... strings){
        try {
            if (prefix == null || strings == null){
                return null;
            }
            StringBuilder stringBuffer = new StringBuilder();
            stringBuffer.append(prefix);
            for (String s :strings){
                stringBuffer.append(DELIMITER).append(s);
            }
            return stringBuffer.toString();
        }catch (Exception e) {
            log.error("RedisUtils.keyBuilder error: ", e);
            return null;
        }
    }
}
